<script setup lang="ts">
  import { ref, watch } from 'vue'
  import { useOrderFinishCheck, useOrderWaitCheckFinishInfo } from './services'
  import { ElMessage } from 'element-plus'
  import { ArrowLeftBold, ArrowRightBold } from '@element-plus/icons-vue'
  import pdf from '@/assets/image/pdf.png'
  import video from '@/assets/image/pages/order/new/video.png'
  import {
    CustomFieldTxtRneder,
    CustomFieldFileRneder,
    CustomFieldRateRneder,
    ArrowState,
    FilesArrowClickParam,
  } from './types'

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: () => false,
    },
    wordId: {
      type: String,
      required: true,
    },
    wordNo: {
      type: String,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'update'): void
  }>()

  const { form, orderFinishCheckLoading, agree, unAgree } = useOrderFinishCheck()

  const {
    orderWaitCheckFinishInfo,
    getOrderWaitCheckFinishInfoLoading,
    getOrderWaitCheckFinishInfo,
  } = useOrderWaitCheckFinishInfo()

  const modalVisible = ref(false)
  const customFieldTxtRender = ref<Array<CustomFieldTxtRneder>>([])
  const customFieldFileRender = ref<Array<CustomFieldFileRneder>>([])
  const customFieldRateRender = ref<Array<CustomFieldRateRneder>>([])

  const onClose = () => {
    form.value.remark = ''
    modalVisible.value = false
    emits('update:modelValue', modalVisible.value)
  }

  const onRejectBtnClick = async () => {
    const res = await unAgree(props.wordId)
    ElMessage({
      type: res.success ? 'success' : 'error',
      message: res.message,
      duration: 5000,
      plain: true,
      showClose: true,
    })
    if (res.success) {
      form.value.remark = ''
      onClose()
      emits('update')
    }
  }

  const onSubmitBtnClick = async () => {
    const res = await agree(props.wordId)
    ElMessage({
      type: res.success ? 'success' : 'error',
      message: res.message,
      duration: 5000,
      plain: true,
      showClose: true,
    })
    if (res.success) {
      form.value.remark = ''
      onClose()
      emits('update')
    }
  }

  // 视频预览弹窗显示状态
  const videoPreviewModalVisible = ref(false)

  // 视频预览地址
  const videoPreviewUrls = ref<Array<string>>([])

  // 视频索引，用来标记当前的视频是第几个
  const videoPreviewIndex = ref(0)
  const handlePreviewVideo = (fieldIndex: number, fileIndex: number) => {
    videoPreviewIndex.value = fileIndex
    videoPreviewModalVisible.value = true
    videoPreviewUrls.value.push(...customFieldFileRender.value[fieldIndex].val)
  }

  /**
   * 视频预览弹窗关闭事件
   */
  const onCloseVideoPreviewModal = () => {
    videoPreviewModalVisible.value = false
    videoPreviewUrls.value = []
    videoPreviewIndex.value = 0
  }

  // 附件预览弹窗显示状态
  const filePreviewModalVisible = ref(false)

  // 附件预览地址
  const filePreviewUrls = ref<Array<string>>([])

  // 附件索引，用来标记当前的附件是第几个
  const filePreviewIndex = ref(0)
  const handlePreviewFile = (fieldIndex: number, fileIndex: number) => {
    filePreviewIndex.value = fileIndex
    filePreviewModalVisible.value = true
    filePreviewUrls.value.push(...customFieldFileRender.value[fieldIndex].val)
  }

  /**
   * 附件预览弹窗关闭事件
   */
  const onCloseFilePreviewModal = () => {
    filePreviewModalVisible.value = false
    filePreviewUrls.value = []
    filePreviewIndex.value = 0
  }

  // 文件列表容器div集合
  const filesRefs = ref<Array<HTMLDivElement> | null>(null)

  // 文件列表容器div左右两边箭头的激活状态集合
  const arrowStates = ref<Array<ArrowState>>([])

  /**
   * 文件列表容器div左右两边箭头的点击事件
   * @param {Object} param - 接收的参数
   * @param {number} param.index - 文件列表容器div的索引
   * @param {string} param.direction - 点击的箭头的方向
   */
  const handleFilesArrowClick = (param: FilesArrowClickParam) => {
    if (filesRefs.value && filesRefs.value.length > 0) {
      if (param.direction === 'right') {
        arrowStates.value[param.index].movedDistance += 100
        if (arrowStates.value[param.index].movedDistance >= 200) {
          arrowStates.value[param.index].movedDistance = 200
          arrowStates.value[param.index].activeArrow = 'left'
        }
        filesRefs.value[param.index].style.transform = `translateX(-${
          arrowStates.value[param.index].movedDistance
        }%)`
      } else {
        arrowStates.value[param.index].movedDistance -= 100
        if (arrowStates.value[param.index].movedDistance <= 0) {
          arrowStates.value[param.index].movedDistance = 0
          arrowStates.value[param.index].activeArrow = 'right'
        }
        filesRefs.value[param.index].style.transform = `translateX(-${
          arrowStates.value[param.index].movedDistance
        }%)`
      }
    }
  }

  watch(
    props,
    async (value) => {
      modalVisible.value = value.modelValue
      if (value.modelValue && value.wordId) {
        await getOrderWaitCheckFinishInfo(value.wordId)
        form.value.id = orderWaitCheckFinishInfo.value.id
        customFieldFileRender.value = []
        customFieldTxtRender.value = []
        customFieldRateRender.value = []
        orderWaitCheckFinishInfo.value.finishOrderTemplates.forEach((template) => {
          template.fieldVals.forEach((field) => {
            if ([1, 2, 3, 4].includes(field.type)) {
              customFieldTxtRender.value.push({
                name: field.name,
                type: field.type,
                val: field.optVos.map((item) => item.optValue).join('、'),
                showLabelTooltip: false,
                showValueTooltip: false,
              })
            }
            if (field.type === 8) {
              customFieldRateRender.value.push({
                name: field.name,
                type: field.type,
                val: field.optVos
                  .map((item) => Number(item.optValue))
                  .reduce((pre, cur) => pre + cur, 0),
                showLabelTooltip: false,
                showValueTooltip: false,
              })
            }
            if ([5, 6, 7].includes(field.type)) {
              arrowStates.value.push({ activeArrow: 'right', index: 0, movedDistance: 0 })
              customFieldFileRender.value.push({
                name: field.name,
                type: field.type,
                val: field.optVos.map((item) => item.optValue),
                showLabelTooltip: false,
                showValueTooltip: false,
              })
            }
          })
        })
      }
    },
    { deep: true, immediate: true },
  )
</script>

<template>
  <div>
    <span @click="modalVisible = true">
      <slot></slot>
    </span>

    <HDialog
      v-model="modalVisible"
      :loading="orderFinishCheckLoading || getOrderWaitCheckFinishInfoLoading"
      title="审核结单"
      :width="900"
      @close="onClose"
    >
      <div class="modal_body">
        <div class="title">
          <div class="line"></div>
          <h3>基本信息</h3>
        </div>

        <div v-if="orderWaitCheckFinishInfo" class="text_rate_info_list">
          <div class="info_item">
            <div class="label">
              <div class="text">工单单号</div>
              <div class="middle">:</div>
            </div>
            <div class="value">{{ props.wordNo }}</div>
          </div>
          <div class="info_item">
            <div class="label">
              <div class="text">申请人员</div>
              <div class="middle">:</div>
            </div>
            <div class="value">{{ orderWaitCheckFinishInfo.applyEmp }}</div>
          </div>
          <div class="info_item">
            <div class="label">
              <div class="text">申请时间</div>
              <div class="middle">:</div>
            </div>
            <div class="value">{{ orderWaitCheckFinishInfo.applyTime }}</div>
          </div>
          <div
            v-for="(field, fieldIndex) in customFieldTxtRender"
            :key="fieldIndex"
            class="info_item"
          >
            <div class="label">
              <h-tooltip-text :height="16" :max-width="52" :text="field.name" text-align="right">
                <div class="text">{{ field.name }}</div>
              </h-tooltip-text>
              <div class="middle">:</div>
            </div>
            <h-tooltip-text :height="16" :max-width="160" :text="field.val" text-align="left">
              <div class="value">{{ field.val }}</div>
            </h-tooltip-text>
          </div>
          <div
            v-for="(field, fieldIndex) in customFieldRateRender"
            :key="fieldIndex"
            class="info_item"
          >
            <div class="label">
              <div class="text">{{ field.name }}</div>
              <div class="middle">:</div>
            </div>
            <div class="value">
              <div class="rate_container">
                <el-rate disabled allow-half :model-value="field.val / 2" />
                <span>{{ field.val }}</span>
              </div>
            </div>
          </div>
        </div>

        <div v-if="orderWaitCheckFinishInfo" class="custom_field_files">
          <div
            v-for="(field, fieldIndex) in customFieldFileRender"
            :key="fieldIndex"
            class="info_item"
          >
            <div class="label">
              <div class="text">{{ field.name }}</div>
              <div class="middle">:</div>
            </div>
            <div class="file_list">
              <div
                v-show="field.val.length >= 6"
                :class="[
                  'arrow',
                  arrowStates[fieldIndex].activeArrow === 'left'
                    ? 'enabled_arrow'
                    : 'disabled_arrow',
                ]"
                @click="handleFilesArrowClick({ index: fieldIndex, direction: 'left' })"
              >
                <i class="iconfont icon-arrow-left"></i>
              </div>
              <div class="list">
                <div ref="filesRefs" class="list_content">
                  <div v-for="(file, fileIndex) in field.val" :key="fileIndex" class="file">
                    <h-image
                      v-show="field.type === 5"
                      :src="file"
                      :width="80"
                      :height="50"
                      :padding="2"
                      fit="contain"
                      :show-del-btn="false"
                      :preview-src-list="field.val"
                      :initial-index="fileIndex"
                    />
                    <h-image
                      v-show="field.type === 6"
                      :src="pdf"
                      :width="80"
                      :height="50"
                      fit="contain"
                      :show-del-btn="false"
                      :is-show-img-preview="false"
                      @preview="handlePreviewFile(fieldIndex, fileIndex)"
                    />
                    <h-image
                      v-show="field.type === 7"
                      :src="video"
                      :width="80"
                      :height="50"
                      fit="contain"
                      :show-del-btn="false"
                      :is-show-img-preview="false"
                      @preview="handlePreviewVideo(fieldIndex, fileIndex)"
                    />
                  </div>
                </div>
              </div>
              <div
                v-show="field.val.length >= 6"
                :class="[
                  'arrow',
                  arrowStates[fieldIndex].activeArrow === 'right'
                    ? 'enabled_arrow'
                    : 'disabled_arrow',
                ]"
                @click="handleFilesArrowClick({ index: fieldIndex, direction: 'right' })"
              >
                <i class="iconfont icon-arrow-right"></i>
              </div>
            </div>
          </div>
        </div>
        <el-form label-position="right" label-width="60">
          <el-form-item label="审核备注:">
            <el-input
              v-model.trim="form.remark"
              maxlength="200"
              show-word-limit
              type="textarea"
              placeholder="请填写备注"
              resize="both"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <HPlainBgButton type="error" is-modal @click="onRejectBtnClick">驳回 </HPlainBgButton>
        <HButton type="primary" is-modal @click="onSubmitBtnClick">通过 </HButton>
        <HButton is-modal @click="onClose">取消</HButton>
      </template>
    </HDialog>

    <!--视频预览弹窗-->
    <HDialog
      v-model="videoPreviewModalVisible"
      title="视频预览"
      :width="800"
      @close="onCloseVideoPreviewModal"
    >
      <div style="display: flex; align-items: center; gap: 12px; justify-content: center">
        <el-button
          type="primary"
          :disabled="videoPreviewIndex === 0"
          :icon="ArrowLeftBold"
          style="padding: 0 14px"
          @click="videoPreviewIndex--"
        />
        <video :src="videoPreviewUrls[videoPreviewIndex]" controls width="600"></video>
        <el-button
          type="primary"
          :disabled="videoPreviewIndex === videoPreviewUrls.length - 1"
          :icon="ArrowRightBold"
          style="padding: 0 14px"
          @click="videoPreviewIndex++"
        />
      </div>
    </HDialog>

    <!--附件预览弹窗-->
    <HDialog
      v-model="filePreviewModalVisible"
      title="附件"
      :width="800"
      @close="onCloseFilePreviewModal"
    >
      <div style="display: flex; align-items: center; gap: 12px; justify-content: center">
        <el-button
          type="primary"
          :disabled="filePreviewIndex === 0"
          :icon="ArrowLeftBold"
          style="padding: 0 14px"
          @click="filePreviewIndex--"
        />
        <iframe :src="filePreviewUrls[filePreviewIndex]" width="600" height="500"></iframe>
        <el-button
          type="primary"
          :disabled="filePreviewIndex === filePreviewUrls.length - 1"
          :icon="ArrowRightBold"
          style="padding: 0 14px"
          @click="filePreviewIndex++"
        />
      </div>
    </HDialog>
  </div>
</template>

<style scoped lang="scss">
  @import './CheckStatementOrder.scss';
</style>
